//保养计划
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { useHistory } from 'react-router-dom';

import {
    Button,
    Form,
    Card,
    Tabs,
    Select,
    Modal,
    message,
    DatePicker,
    Input,
    TreeSelect,
} from 'antd';

import { get, post } from '../../axios/http';
import { convertRes2Blob, formatTime, BasicTable } from '../../utils/x.js';
import { euqApplicationName } from '../../config';

const { TabPane } = Tabs;
const { Option } = Select;


/**
 * 调整计划时间表单
 */
const MaintenanceWorkPlanForm2 = React.forwardRef(function MaintenanceWorkPlanForm2({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue }, mode, onEvent }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    const validatorDate = useCallback((rule, value, callback) => {
        const date1 = getFieldValue('maintainStartTime');
        const date2 = getFieldValue('maintainEndTime');
        if (date1 > date2) {
            callback('开始时间不能大于结束时间');
            return;
        }
        callback();
    }, []);

    return (
        <Form>
            <Form.Item label="开始时间">
                {getFieldDecorator("maintainStartTime", {
                    rules: [
                        {
                            required: true,
                        },
                        {
                            validator: validatorDate,
                        },
                    ],
                })(
                    <DatePicker />
                )}
            </Form.Item>
            <Form.Item label="结束时间">
                {getFieldDecorator("maintainEndTime", {
                    rules: [
                        {
                            required: true,
                        },
                        {
                            validator: validatorDate,
                        },
                    ],
                })(
                    <DatePicker />
                )}
            </Form.Item>
            {getFieldDecorator("id")(
                <Input type="hidden" />
            )}
        </Form>
    );
});

/**
 * 表格
 */
function MaintenanceWorkPlanTable1({ data, selectedKeys, pagination, loading, onEvent }) {
    const handleDetailClick = useCallback((e) => {
        e.preventDefault();
        if (typeof onEvent !== 'function') {
            return;
        }
        const action = e.currentTarget.getAttribute('data-action');
        switch (action) {
            case 'detail': {
                onEvent({ type: 'DETAIL_ITEM', id: Number(e.currentTarget.getAttribute('data-id')) });
                break;
            }
            case 'stop': {
                onEvent({ type: 'STOP_ITEM', id: Number(e.currentTarget.getAttribute('data-id')), isUse: Number(e.currentTarget.getAttribute('data-use')) });
                break;
            }
            default:
                break;
        }
    }, [onEvent])

    const tableColumns = [
        {
            title: '计划序号',
            dataIndex: 'id',
        },
        {
            title: '操作',
            render: (text, row, index) => {
                const canStop = ['未开始', '待派工/接单', '计划已超期'].includes(row.maintainPlanStatus);
                const text2 = row.isUse === 0 ? '启用' : '停用';
                return (
                    <>
                        <a href="#" style={{ marginRight: 10 }} data-action="detail" data-id={row.id} onClick={handleDetailClick}>详细</a>
                        {canStop && <a href="#" data-action="stop" data-id={row.id} data-use={row.isUse} onClick={handleDetailClick}>{text2}</a>}
                    </>
                );
            },
        },
        {
            title: '状态',
            dataIndex: 'maintainPlanStatus',
            render: (text, row, index) => {
                return row.beOverdue ? row.beOverdue : text;
            },
        },
        {
            title: '设备编号',
            dataIndex: 'equipmentCode',
        },
        {
            title: '设备名称',
            dataIndex: 'equipmentName',
        },
        {
            title: '保养组',
            dataIndex: 'maintainTeamName',
        },
        {
            title: '部门',
            dataIndex: 'equipmentDepart',
        },
        {
            title: '上次保养时间',
            dataIndex: 'maintainLastTime',
        },
        {
            title: '下次计划保养时间',
            dataIndex: 'maintainStartTime',
        },
        {
            title: '时间间隔',
            dataIndex: 'loopCycle',
        },
        {
            title: '循环方式',
            dataIndex: 'loopStyle',
            render: (text) => {
                switch (text) {
                    case 0:
                        return '单次';
                    case 1:
                        return '多次';
                    default:
                        break;
                }
            }
        },
        {
            title: '保养级别',
            dataIndex: 'maintainLevel',
        },
    ];
    const tableRowSelection = {
        selectedRowKeys: selectedKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            onEvent({ type: 'UPDATE_SELECTED', keys: selectedRowKeys, rows: selectedRows });
        },
    };

    return (
        <BasicTable
            rowKey="id"
            dataSource={data}
            columns={tableColumns}
            rowSelection={tableRowSelection}
            pagination={pagination}
            loading={loading} />
    );
}

/**
 * 标签
 */
function MaintenanceWorkPlanTabs1({ children, onEvent }) {
    const handleExtraClick = useCallback((e) => {
        onEvent && onEvent(e.currentTarget.getAttribute('data-action'));
    }, [onEvent]);

    const extraContent = (
        <div>
            <Button icon="plus" type="primary" style={{ marginLeft: 5 }} data-action="add" onClick={handleExtraClick}>添加计划</Button>
            <Button icon="swap" type="primary" style={{ marginLeft: 5 }} data-action="modifyTime" onClick={handleExtraClick}>调整计划执行时间</Button>
            <Button icon="play-circle" type="primary" style={{ marginLeft: 5 }} data-action="execute" onClick={handleExtraClick}>执行计划</Button>
            <Button icon="usergroup-add" type="primary" style={{ marginLeft: 5 }} data-action="send" onClick={handleExtraClick}>派工</Button>
            <Button icon="delete" type="danger" style={{ marginLeft: 5 }} data-action="delete" onClick={handleExtraClick}>删除</Button>
            <Button icon="arrow-down" type="default" style={{ marginLeft: 5 }} data-action="export" onClick={handleExtraClick}>导出</Button>
        </div>
    );

    return (
        <Tabs tabBarExtraContent={extraContent}>
            <TabPane tab="保养计划" key="1">
                {children}
            </TabPane>
        </Tabs>
    );
}

/**
 * 搜索表单
 */
function MaintenanceWorkPlanForm1({ form, form: { getFieldDecorator }, onSubmit }) {
    const [treeData1, setTreeData1] = useState([]);

    const handleSubmit = useCallback((e) => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            onSubmit && onSubmit(values);
        });
    }, [onSubmit]);

    const statusList = ['未开始', '待派工/接单', '待保养', '保养中', '已停用', '工单已超期', '计划已超期'];

    useEffect(() => {
        (async () => {
            try {
                const res1 = await get(euqApplicationName + '/currency/queryTeam');
                res1 && setTreeData1([{ id: null, name: '全部' }, ...res1.data].map(item => {
                    return {
                        value: item.id,
                        title: item.name,
                    };
                }));
            } catch (err) {}
        })();
    }, []);

    return (
        <Form layout="inline" onSubmit={handleSubmit}>
            <Form.Item label="计划状态">
                {getFieldDecorator('maintainStatus')(
                    <Select style={{ minWidth: 120 }}>
                        <Option value={null}>全部</Option>
                        {statusList.map((text, index) => (
                            <Option key={index} value={text}>{text}</Option>
                        ))}
                    </Select>
                )}
            </Form.Item>
            <Form.Item label="计划时间">
                {getFieldDecorator('planTime')(
                    <Select style={{ minWidth: 120 }}>
                        <Option value={null}>全部</Option>
                        <Option value={0}>今日</Option>
                        <Option value={1}>本周</Option>
                        <Option value={2}>本月</Option>
                    </Select>
                )}
            </Form.Item>
            <Form.Item label="保养班组">
                {getFieldDecorator('maintainTeamId')(
                    <TreeSelect style={{ minWidth: 120 }} treeData={treeData1} />
                )}
            </Form.Item>
            <Form.Item label="相关性">
                {getFieldDecorator('userId')(
                    <Select style={{ minWidth: 120 }}>
                        <Option value={null}>全部</Option>
                        <Option value={Number(localStorage.getItem('userId'))}>我作为技术人员</Option>
                    </Select>
                )}
            </Form.Item>
            <Form.Item>
                <Button type="primary" htmlType="submit">搜索</Button>
            </Form.Item>
        </Form>
    );
}

/**
 * 主组件
 */
function MaintenanceProgram() {
    const history = useHistory();

    const [data, setData] = useState([]);
    const [dataQuery, setDataQuery] = useState({});
    const [pagination, setPagination] = useState({});
    const [isDataLoading, setIsDataLoading] = useState(false);
    const [selected1, setSelected1] = useState({ key: [], row: [] });

    const [isModal2Open, setIsModal2Open] = useState(false);
    const [modal2Data, setModal2Data] = useState({});

    const fetchData = (params = {}, exact = false) => {
        setDataQuery(prev => {
            return exact ? params : { ...prev, ...params };
        });
    };

    const exportExcel = useCallback((list = []) => {
        (async () => {
            try {
                const reqData = list.map(item => `idList=${item}`).join('&');
                const url = list.length === 0 ? euqApplicationName + '/equipmentMaintainPlan/exportEquipmentMaintainPlanExcel' : `${euqApplicationName}/equipmentMaintainPlan/exportEquipmentMaintainPlanExcel?${reqData}`;
                const res = await get(url, { responseType: 'blob' });
                convertRes2Blob(res, '保养计划');
            } catch (err) {
                Modal.error({
                    title: '发生了错误',
                    content: err.message,
                });
                console.error(err);
            }
        })();
    }, []);

    const handleForm1Submit = useCallback((values) => {
        fetchData(values, true);
    }, []);

    const handleTabs1Event = useCallback((action) => {
        // console.log('selected1', selected1);
        switch (action) {
            case 'add': {
                history.push('/MaintenanceProgramDetail');
                break;
            }
            case 'modifyTime': {
                if (selected1.key.length !== 1) {
                    Modal.info({
                        title: '必须选择一个项目',
                    });
                    return;
                }
                if (selected1.row[0].isUse === 0) {
                    Modal.info({
                        title: '停用时无法进行该操作',
                    });
                    return;
                }
                setModal2Data({
                    id: selected1.key[0],
                });
                setIsModal2Open(true);
                break;
            }
            case 'execute': {
                if (selected1.key.length !== 1) {
                    Modal.info({
                        title: '必须选择一个项目',
                    });
                    return;
                }
                if (selected1.row[0].isUse === 0) {
                    Modal.info({
                        title: '停用时无法进行该操作',
                    });
                    return;
                }
                if (!['未开始', '待派工/接单', '计划已超期'].includes(selected1.row[0].maintainPlanStatus)) {
                    Modal.error({
                        title: '该计划正在执行中，无法重复提交',
                    });
                    return;
                }
                history.push(`/MaintenanceProgramDetail2/${selected1.key[0]}`);
                break;
            }
            case 'send': {
                if (selected1.key.length !== 1) {
                    Modal.info({
                        title: '必须选择一个项目',
                    });
                    return;
                }
                if (selected1.row[0].isUse === 0) {
                    Modal.info({
                        title: '停用时无法进行该操作',
                    });
                    return;
                }
                if (!['未开始', '待派工/接单', '计划已超期'].includes(selected1.row[0].maintainPlanStatus)) {
                    Modal.error({
                        title: '该计划正在执行中，无法重复提交',
                    });
                    return;
                }
                history.push(`/MaintenanceProgramDetail3/${selected1.key[0]}`);
                break;
            }
            case 'delete': {
                if (selected1.key.length < 1) {
                    Modal.info({
                        title: '需要至少选择一个项目',
                    });
                    return;
                }
                Modal.confirm({
                    title: '你确定要删除这些项目吗？',
                    onOk() {
                        (async () => {
                            try {
                                const reqData = {
                                    ids: selected1.key.join(','),
                                };
                                // console.log(reqData); return;
                                const res = await get(euqApplicationName + '/equipmentMaintainPlan/deleteEquipmentMaintainPlan', { params: { ids: reqData.ids } });
                                message.info('删除成功');
                                setSelected1({ key: [], row: [] });
                                fetchData();
                            } catch (err) {
                                Modal.error({
                                    title: '发生了错误',
                                    content: err.message,
                                });
                            }
                        })();
                    },
                });
                break;
            }
            case 'export': {
                if (selected1.key.length < 1) {
                    Modal.confirm({
                        title: '当前没有选择项目，将会导出所有数据。是否继续？',
                        onOk() {
                            exportExcel();
                        },
                    });
                } else {
                    exportExcel(selected1.key);
                }
                break;
            }
            default:
                break;
        }
    }, [selected1]);

    const handleTable1Event = useCallback((e) => {
        switch (e.type) {
            case 'DETAIL_ITEM': {
                history.push(`/MaintenanceProgramDetail/${e.id}`);
                break;
            }
            case 'STOP_ITEM': {
                const reqData = {
                    id: e.id,
                    isUse: e.isUse === 1 ? 0 : 1,
                    _: Date.now(),
                };
                // console.log(reqData); return;
                (async () => {
                    try {
                        const res = await get(euqApplicationName + '/equipmentMaintainPlan/stopPlan', { params: reqData });
                        message.info('修改成功');
                        setSelected1({ key: [], row: [] });
                        fetchData();
                    } catch (err) {}
                })();
                break;
            }
            case 'UPDATE_SELECTED': {
                setSelected1({ key: e.keys, row: e.rows });
                break;
            }
            default:
                break;
        }
    }, []);

    const Form1Wrap = useMemo(() => {
        return Form.create()(MaintenanceWorkPlanForm1);
    }, []);

    // 调整计划时间窗口
    const form2Ref = useRef();

    const Form2Wrap = Form.create({
        mapPropsToFields(props) {
            const { data } = props;
            return {
                id: Form.createFormField({ value: data.id }),
            };
        }
    })(MaintenanceWorkPlanForm2);

    const handleModal2Ok = useCallback(() => {
        form2Ref.current.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            const reqData = {
                id: values.id,
                startTime: formatTime(values.maintainStartTime),
                endTime: formatTime(values.maintainEndTime),
            };
            // console.log(reqData); return;
            (async () => {
                try {
                    const res = await post(euqApplicationName + '/equipmentMaintainPlan/adjustPlanTime', { data: reqData });
                    message.info('修改成功');
                    setIsModal2Open(false);
                    fetchData();
                } catch (err) {}
            })();
        });
    }, []);

    const handleModal2Cancel = useCallback(() => {
        setIsModal2Open(false);
    }, []);


    useEffect(() => {
        (async () => {
            setIsDataLoading(true);
            try {
                const res = await get(euqApplicationName + '/equipmentMaintainPlan/findEquipmentMaintainPlan', { params: dataQuery });
                setData(res.data);
                setPagination({
                    current: res.pageNum,
                    pageSize: res.pageSize,
                    total: res.total,
                    onChange(page) {
                        setDataQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                });
            } catch (err) {}
            setIsDataLoading(false);
        })();
    }, [dataQuery]);

    return (
        <>
            <Card size="small" style={{ marginBottom: 10 }}>
                <Form1Wrap onSubmit={handleForm1Submit} />
            </Card>
            <Card size="small">
                <MaintenanceWorkPlanTabs1 onEvent={handleTabs1Event}>
                    <MaintenanceWorkPlanTable1 data={data} selectedKeys={selected1.key} pagination={pagination} loading={isDataLoading} onEvent={handleTable1Event} />
                </MaintenanceWorkPlanTabs1>
            </Card>
            <Modal title="调整计划时间" visible={isModal2Open} onOk={handleModal2Ok} onCancel={handleModal2Cancel}>
                <Form2Wrap wrappedComponentRef={form2Ref} data={modal2Data} />
            </Modal>
        </>
    )
}

export default MaintenanceProgram;
